import React, { useEffect, useState } from "react";
import { Outlet, useLocation } from "umi";
import music1 from "../assets/p1/music.mp3";
import music2 from "../assets/p2/music.mp3";

export default function Layout() {
	const location = useLocation();
	const [currentMusic, setCurrentMusic] = useState("");
	const [musicStarted, setMusicStarted] = useState(false);

	// 根据当前页面路由决定背景音乐
	useEffect(() => {
		var newMusic = ""; // 新的音乐路径

		if (location.pathname === "/" || location.pathname.startsWith("/p1")) {
			newMusic = music1;
		} else if (location.pathname.startsWith("/p2")) {
			newMusic = music2;
		}

		// 如果音乐真地发生了改变，我们需要重设一些变量
		if (newMusic != currentMusic) {
			setCurrentMusic(newMusic); // 更新当前音乐

			if (newMusic != "") {
				// 如果新的音乐不是空的
				const audioElement =
					document.getElementById("background-music");
				audioElement.src = newMusic; // 拉取新的音乐
				audioElement.load(); // 重新加载音乐
			}

			setMusicStarted(false); // 让音乐可以重新播放
		}
	}, [location]);

	// 处理音乐更改
	useEffect(() => {
		const audioElement = document.getElementById("background-music");

		if (audioElement && currentMusic !== "") {
			audioElement.src = currentMusic; // 更改音乐源
			audioElement.load(); // 重新加载音乐
		}
	}, [currentMusic]);

	// 处理音乐播放
	useEffect(() => {
		const audioElement = document.getElementById("background-music");

		if (audioElement) {
			const startMusic = () => {
				if (!musicStarted) {
					const playPromise = audioElement.play();

					if (playPromise !== undefined) {
						playPromise
							.then(() => {
								setMusicStarted(true);
								document.removeEventListener(
									"mousemove",
									startMusic
								);
							})
							.catch(_ => {
								// 如果无法播放，添加mousemove事件尝试再次播放
								document.addEventListener(
									"mousemove",
									startMusic
								);
							});
					}
				}
			};

			// 开始尝试播放
			startMusic();

			return () => {
				document.removeEventListener("mousemove", startMusic);
			};
		}
	}, [musicStarted]);

	return (
		<>
			<Outlet />
			<audio autoPlay loop id="background-music">
				<source src={currentMusic} type="audio/mpeg" />
				您的浏览器不支持 audio 元素。
			</audio>
		</>
	);
}
